package com.edgclub.edg.activity;


import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.edgclub.edg.GuZhiApplication;
import com.edgclub.edg.R;
import com.edgclub.edg.api.ApiConfig;
import com.edgclub.edg.model.TaskBeanData;
import com.edgclub.edg.model.User;
import com.edgclub.edg.shareapi.ShareSDKApi;
import com.edgclub.edg.utils.util.CommonUtils;
import com.edgclub.edg.utils.util.CryptUtil;
import com.edgclub.edg.utils.util.JSONHelper;
import com.edgclub.edg.utils.util.JsonUtil;
import com.edgclub.edg.utils.util.StringUtils;
import com.edgclub.edg.utils.util.UserPrefUtils;
import com.google.gson.reflect.TypeToken;

import java.util.HashMap;
import java.util.TreeMap;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;


public class GzWebViewActivityNoTitle extends GzBaseTooolBarActivity implements
        View.OnClickListener {
    WebView webView = null;
    private ProgressBar mProgressBar;
    private String opneUrl="";
    private UserPrefUtils userPrefUtil;
    private boolean isHasTitle , right_btn;
    private RelativeLayout back_btn;
    private ImageView btn_refresh;
    private boolean startlink;
    @Override
    public int getContentView() {
        return R.layout.activity_webview_layout1;
    }

    @Override
    public void setTitleBarView() {
        setStatusBarHeight(true);
        userPrefUtil = new UserPrefUtils(this);
//        setCustomActionBar();
        opneUrl=getIntent().getStringExtra("url");

//        opneUrl="http://120.24.78.166:8088/h5/EDG3.0/zillionaire/index.html?gzno=673982129&gameId=10";
//        isHasTitle=getIntent().getBooleanExtra("isHasTitle",true);
//        right_btn=getIntent().getBooleanExtra("right_btn",false);
//        if (right_btn){
//            btn_more_menu.setVisibility(View.GONE);
//        }else{
//            btn_more_menu.setVisibility(View.VISIBLE);
//            btn_more_menu.setOnClickListener(this);
//        }
//        opneUrl = "http://120.24.78.166:8088/h5/EDG3.0/experience/experience.html";
//        startlink=getIntent().getBooleanExtra("startlink",false);
//        if(null!=getIntent().getStringExtra("actbarTitle") )
//            title.setText(getIntent().getStringExtra("actbarTitle") + "");
//        main_back.setVisibility(View.GONE);
//        close_web.setVisibility(View.VISIBLE);
//        close_web.setOnClickListener(this);
        mProgressBar = (ProgressBar) findViewById(R.id.progress_bar1);
    }

    @Override
    public void initView() {
        webView = (WebView) this.findViewById(R.id.webview);
        back_btn = (RelativeLayout) findViewById(R.id.back_btn);
        back_btn.setOnClickListener(this);
//        btn_refresh= (ImageView) this.findViewById(R.id.btn_refresh1);
//        btn_refresh.setOnClickListener(this);
        WebSettings settings = webView.getSettings();
//        // 自适应屏幕
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        settings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        settings.setJavaScriptEnabled(true);
        settings.setDatabaseEnabled(true);
        settings.setDomStorageEnabled(true);
        webView.setWebViewClient(new WebViewClient() {
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                //handler.cancel(); // Android默认的处理方式
                handler.proceed();  // 接受所有网站的证书
                //handleMessage(Message msg); // 进行其他处理
            }
        });

        webView.addJavascriptInterface(new InJavaScriptLocalObj(), "local_obj");
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setDownloadListener(new MyDownLoadListener());

        webView.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                mProgressBar.setProgress(newProgress);
            }
        });

        webView.setWebViewClient(new WebViewClient() {
            private int running = 0;

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                mProgressBar.setVisibility(View.VISIBLE);
//                if((!isHasTitle&&!"".equals(view.getTitle()+ ""))||!"".equals(view.getTitle()+ ""))
//                    title.setText(view.getTitle()+ "");
                    url = url.replaceAll("\\{gzno\\}", userPrefUtil.getGzno());
                if (!url.contains("gzinfo.html")) {
                    running++;
                    view.loadUrl(url);// 使用当前WebView处理跳转
                } else {
                    try {
                        String uid = url.substring(url.lastIndexOf("=") + 1, url.length());
                        User user = new User();
                        user.setId(uid);
                        Intent intent = new Intent(GzWebViewActivityNoTitle.this, UserInfoOtherActivity.class);
                        intent.putExtra("user", user);
                        startActivity(intent);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                return true;// true表示此事件在此处被处理，不需要再广播


            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                running = Math.max(running, 1); // First request move it to 1.
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                try {
                    if (--running == 0) {
                        mProgressBar.setProgress(0);
                        mProgressBar.setVisibility(View.GONE);
                    }
                    if (view == null) {
                        view = webView;
                    }
                    view.loadUrl("javascript:window.local_obj.showShareImage(document.getElementsByTagName('h777')[0].innerHTML);");
                    view.loadUrl("javascript:window.local_obj.showShareContent(document.getElementsByTagName('h999')[0].innerHTML);");
                    view.loadUrl("javascript:window.local_obj.showShareTitle(document.getElementsByTagName('h888')[0].innerHTML);");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onReceivedError(WebView view, int errorCode,
                                        String description, String failingUrl) {
                Toast.makeText(GzWebViewActivityNoTitle.this, description,
                        Toast.LENGTH_SHORT).show();
                mProgressBar.setVisibility(View.GONE);
            }
        });


    }
    /**
     * webView下载类
     */
    private class MyDownLoadListener implements DownloadListener {
        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
            Uri uri = Uri.parse(url);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
        }
    }
    @Override
    public void initData() {
        webView.loadUrl(opneUrl);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back_btn:
                finish();
                break;
//            case R.id.close_web:
//                if(startlink){
//                    Intent i=new Intent(this,GzLoginActivity.class);
//                    startActivity(i);
//                }
//                finish();
//                break;
//            case R.id.btn_refresh1:
//                webView.reload();
//                break;
//            case R.id.btn_more_menu:
//                mHandler.post(new Runnable() {
//                    @Override
//                    public void run() {
//                        webView.loadUrl("javascript:window.local_obj.showShareImage(document.getElementsByTagName('h777')[0].innerHTML);");
//                        webView.loadUrl("javascript:window.local_obj.showShareContent(document.getElementsByTagName('h999')[0].innerHTML);");
//                        webView.loadUrl("javascript:window.local_obj.showShareTitle(document.getElementsByTagName('h888')[0].innerHTML);");
//                    }
//                });
//                showShare();
//                break;
        }
    }
    private String getShareImageUrl() {
        String imageUrl = shareImage;
        if (TextUtils.isEmpty(shareImage)) {
            imageUrl = ShareSDKApi.SHAREIMAGE;
        }
        return imageUrl;
    }
    private void showShare() {
        ShareSDKApi.showShare(this, shareTitle,
                shareContent, opneUrl+"&app=false", getShareImageUrl(), new PlatformActionListener() {
                    @Override
                    public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                        Message message = new Message();
                        message.what = 0;
                        message.obj = platform;
                        shareHandler.sendMessage(message);
                    }

                    @Override
                    public void onError(Platform platform, int i, Throwable throwable) {
                        Message message = new Message();
                        message.what = 1;
                        message.obj = platform;
                        shareHandler.sendMessage(message);
                    }

                    @Override
                    public void onCancel(Platform platform, int i) {
                        Message message = new Message();
                        message.what = 2;
                        message.obj = platform;
                        shareHandler.sendMessage(message);
                    }
                });
    }

    Handler shareHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Platform platform = (Platform) msg.obj;
            if (msg.what == 0) {
                showToast(StringUtils.getString(R.string.share_yes));
            } else if (msg.what == 1) {
                if (QQ.NAME.equals(platform.getName())) {
                    if (CommonUtils.checkPackage(GzWebViewActivityNoTitle.this,
                            "com.tencent.mobileqq")
                            || CommonUtils.checkPackage(GzWebViewActivityNoTitle.this,"com.tencent.qqlite")) {
                        Platform googlePlus1 = ShareSDK.getPlatform(QQ.NAME);
                        googlePlus1.SSOSetting(false);  //设置false表示使用SSO授权方式
                        googlePlus1.showUser(null);
                    }else{
                        showToast("没有安装QQ客户端");
                    }
                }  else if (Wechat.NAME.equals(platform.getName())){
                    if (CommonUtils.checkPackage(GzWebViewActivityNoTitle.this,
                            "com.tencent.mm")) {
                        Platform googlePlus3 = ShareSDK.getPlatform(Wechat.NAME);
                        googlePlus3.SSOSetting(false);  //设置false表示使用SSO授权方式
                        googlePlus3.showUser(null);
                    } else {
                        showToast("没有安装微信客户端");
                    }

                }else {
                    showToast(StringUtils.getString(R.string.share_no));
                }
            } else if (msg.what == 2) {
                showToast(StringUtils.getString(R.string.share_del));
            }
        }
    };

    /**
     * //     *  android sdk api >= 17 时需要加@JavascriptInterface
     * //     * @author fei
     * //     *
     * //
     */
    private String shareTitle = "";
    private String shareImage = "";
    private String shareContent = "";
    private String signText="";
    Handler mHandler=new Handler();
    final class InJavaScriptLocalObj {
        @JavascriptInterface
        public void showShareContent(String content) {
            if (!"".equals(content)) {
                shareContent = content;
            }
        }

        @JavascriptInterface
        public void showShareTitle(String title) {
            if (!"".equals(title)) {
                shareTitle = title;
            }
        }

        @JavascriptInterface
        public void showShareImage(String image) {
            if (!"".equals(image)) {
                shareImage = image;
            }
        }

        @JavascriptInterface
        public void setInfo() {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    User user=userPrefUtil.getUser();
                    user.setPsw("");
                    user.setOldPwd("");
                    user.setNewPwd("");
                    user.setVersion(GuZhiApplication.getInstance().getVersion());
                    String userjson= JsonUtil.getJsonStr(user);
                    webView.loadUrl("javascript:getUserInfo('"+userjson+"')");
                }
            });
        }
        @JavascriptInterface
        public void setSign(final String sign) {
            if (null != sign && !"".equals(sign)) {
                TreeMap<String, String> params = new TreeMap<>();
                params = JsonUtil.getMode(sign, new TypeToken<TreeMap<String, String>>(){}.getType());
                signText= CryptUtil.sign(params, ApiConfig.HTTP_KEY);
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        webView.loadUrl("javascript:getSign2('"+signText+"')");
                        signText="";
                    }
                });
            }
        }

        @JavascriptInterface
        public void TaskComplete(final String str) {
            if (null != str && !"".equals(str)) {
                try {
                    if (JSONHelper.isSuccess(str)) {
                        TaskBeanData aaskBeanData = JsonUtil.getMode(str, TaskBeanData.class);
                        StringUtils.postToast2(GzWebViewActivityNoTitle.this, aaskBeanData.getData().getName() + "", aaskBeanData.getData().getGold() + "");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    }
    // 默认点回退键，会退出Activity，需监听按键操作，使回退在WebView内发生
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        try {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                if (null != webView && webView.canGoBack()) {
                    webView.goBack();
                    return true;
                } else {
                    if(startlink){
                        Intent i=new Intent(this,GzLoginActivity.class);
                        startActivity(i);
                    }
                    finish();
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
        }

        return super.onKeyDown(keyCode, event);
    }
}
